package com.huang.rabbitmq.routing;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/*
*   简单模式
*
* */
public class Consumer {
    private static Runnable runnable=new Runnable() {
        @Override
        public void run() {
            {
                //1 创建连接工程
                ConnectionFactory connectionFactory = new ConnectionFactory();
                connectionFactory.setHost("192.168.56.10");
                connectionFactory.setPort(5672);
                connectionFactory.setUsername("admin");
                connectionFactory.setPassword("admin");
                connectionFactory.setVirtualHost("/");
                String queueName = Thread.currentThread().getName();
                Connection connection=null;
                Channel channel =null;
                //2  创建连接 connection
                try {
                    connection=connectionFactory.newConnection("消费者");
                    //3通过连接通道 获取 Channel
                    channel = connection.createChannel();
                    //4 通过创建的交换机  声明队列 绑定关系  路由key 发送消息和接收消息

                    channel.basicConsume(queueName,true, new DeliverCallback() {
                        @Override
                        public void handle(String s, Delivery message) throws IOException {
                            System.out.println( queueName+"接收到消息，消息是"+new String(message.getBody(),"UTF-8"));
                        }
                    },new CancelCallback(){
                        public void handle(String consumeTag) throws IOException {
                            System.out.println("接受消息失败");
                        }
                    });


                    System.out.println("开始接受消息");
                    System.in.read();


                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 7关闭通道
                    //8关闭连接
                    if(channel!=null && connection!=null){
                        try {
                            channel.close();
                            connection.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (TimeoutException e) {
                            e.printStackTrace();
                        }

                    }

                }

            }
        }
    };

    public static void main(String[] args) {
        new Thread(runnable,"queue5").start();
        new Thread(runnable,"queue6").start();
        new Thread(runnable,"queue7").start();
    }

}
